from venv import logger

import mistune
from flask.logging import default_handler
from flask import Flask, render_template, request, jsonify
import sqlite3
import os
import requests
from openai import OpenAI
from bs4 import BeautifulSoup

app = Flask(__name__)

# 初始化数据库
DATABASE = 'conversations.db'


app.logger.addHandler(default_handler)



@app.route('/')
@app.route('/chatWithAI')
def chatWithAI():
    return render_template('user/chatWithAI.html')

@app.route('/chat', methods=['POST'])
def chat():
    message = request.json.get('message')
    client = OpenAI(
        # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # 如何获取API Key：https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
    )

    # 调用模型生成回复
    prompt = "你是一名儿童保健医生，回答70字以内"
    completion = client.chat.completions.create(
        model="qwen-plus",
        # model="deepseek-r1",
        max_tokens=70,
        # max_completion_tokens=100,
        # stop=["\n","。"],
        messages=[
            {'role': 'user', 'content': message},
            {'role': 'assistant', 'content': prompt}
        ])

    if completion:
        ai_response = completion.choices[0].message.content
        print(ai_response)
        # 将 Markdown 转换为 HTML
        markdown = mistune.create_markdown()
        html = markdown(ai_response)
        # 使用 BeautifulSoup 提取纯文本
        soup = BeautifulSoup(html, 'html.parser')
        plain_text = soup.get_text()

        return jsonify({'response': plain_text})
    
    return jsonify({'error': 'API请求失败'}), 500

def init_db():
    with app.app_context():
        conn = sqlite3.connect(DATABASE)
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS conversations
                     (id INTEGER PRIMARY KEY AUTOINCREMENT,
                     user_input TEXT,
                     ai_response TEXT,
                     timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
        conn.commit()
        conn.close()

if __name__ == '__main__':
    init_db()
    app.run(debug=True)